package com.choosefine.it.basedata.service;

import com.choosefine.it.basedata.dao.WorkTypeClassMapper;
import com.choosefine.it.basedata.model.WorkTypeClass;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("workTypeClassService")
public class WorkTypeClassService{

	@Resource
	WorkTypeClassMapper workTypeClassMapper;
	
	public int deleteByPrimaryKey(Integer id) {
		int num = 0;
		WorkTypeClass deleteWorkTypeClassUp = workTypeClassMapper.selectWorkTypeClassBySortNum(id);
		WorkTypeClass deleteWorkTypeClass = workTypeClassMapper.selectByPrimaryKey(id);
		if(null != deleteWorkTypeClassUp){
			deleteWorkTypeClassUp.setSortNum(deleteWorkTypeClass.getSortNum());
			num += workTypeClassMapper.updateByPrimaryKeySelective(deleteWorkTypeClassUp);
		}
		num += workTypeClassMapper.deleteByPrimaryKey(id);
		return num;
	}

	public int insert(WorkTypeClass record) throws BusinessException{
		int count = workTypeClassMapper.checkWorkTypeClassInsert(record.getClassname());
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		int num = 0;
		WorkTypeClass lastWorkTypeClass = workTypeClassMapper.selectWorkTypeClassBySortNum(0);
		if(null != lastWorkTypeClass){
			record.setSortNum(-1);
			num += workTypeClassMapper.insertSelective(record);
			record = workTypeClassMapper.selectWorkTypeClassBySortNum(-1);
			lastWorkTypeClass.setSortNum(record.getId());
			record.setSortNum(0);
			num += workTypeClassMapper.updateByPrimaryKeySelective(record);
			num += workTypeClassMapper.updateByPrimaryKeySelective(lastWorkTypeClass);
		}else{
			record.setSortNum(0);
			num += workTypeClassMapper.insertSelective(record);
		}
		return num;
	}

	public int update(WorkTypeClass record) throws BusinessException {
		int count = workTypeClassMapper.checkWorkTypeClassInsert(record.getClassname());
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		return workTypeClassMapper.updateByPrimaryKeySelective(record);
	}

	public WorkTypeClass findByPrimaryKey(Integer id) {
		
		return workTypeClassMapper.selectByPrimaryKey(id);
	}

	public List<WorkTypeClass> selectAll() {
		
		return workTypeClassMapper.selectAll();
	}

	public PageInfo<WorkTypeClass> findAllByPage(Map<String, Object> t,
			Integer pageNo, Integer pageSize) throws BusinessException{
		List<WorkTypeClass> getList = workTypeClassMapper.selectAll();
		pageNo = pageNo == null?1:pageNo;
		pageSize = pageSize == null?10:pageSize;
		if(getList.size()==0){
			return new PageInfo<WorkTypeClass>();
		}
		List<WorkTypeClass> returnList = WorkTypeClassOrder(getList);
		int start = (pageNo-1) * pageSize;
		if (start > returnList.size()) {
			return new PageInfo<WorkTypeClass>();
		}
		int end = pageNo * pageSize;
		end = end > returnList.size()?returnList.size()-1:end;
		returnList = returnList.subList(start , end);
		return new PageInfo<WorkTypeClass>(returnList);
	}
	public List<WorkTypeClass> findAllByPage() throws BusinessException{
		List<WorkTypeClass> getList = workTypeClassMapper.selectAll();
		if(getList.size()==0){
			return new ArrayList<WorkTypeClass>();
		}
		List<WorkTypeClass> returnList = WorkTypeClassOrder(getList);
		return returnList;
	}
	
	public WorkTypeClass getWorkTypeClassListByName(String typeclassname){
		return workTypeClassMapper.selectWorkTypeClassListByName(typeclassname);
	}
	public PageInfo<WorkTypeClass> selectWorkTypeClassListByName(String typeclassname, Integer pageSize, Integer pageNum){
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<WorkTypeClass>(workTypeClassMapper.getWorkTypeClassListByName(typeclassname));
	}
	public int workTypeClassOrderUp(Integer fromId,Integer toId){
		int num = 0;
		WorkTypeClass fromWorkTypeClass = null;
		WorkTypeClass fromWorkTypeClassUp = null;
		WorkTypeClass toWorkTypeClassUp = null;
		fromWorkTypeClass = workTypeClassMapper.selectByPrimaryKey(fromId);
		fromWorkTypeClassUp = workTypeClassMapper.selectWorkTypeClassBySortNum(fromId);
		toWorkTypeClassUp = workTypeClassMapper.selectWorkTypeClassBySortNum(toId);
		if(toWorkTypeClassUp == null){
			fromWorkTypeClassUp.setSortNum(fromWorkTypeClass.getSortNum());
			fromWorkTypeClass.setSortNum(toId);
		}else{
			fromWorkTypeClassUp.setSortNum(fromWorkTypeClass.getSortNum());
			fromWorkTypeClass.setSortNum(toId);
			toWorkTypeClassUp.setSortNum(fromId);
		}
		if(null != toWorkTypeClassUp){
			num += workTypeClassMapper.updateByPrimaryKeySelective(toWorkTypeClassUp);
		}
		num += workTypeClassMapper.updateByPrimaryKeySelective(fromWorkTypeClass);
		num += workTypeClassMapper.updateByPrimaryKeySelective(fromWorkTypeClassUp);
		return num;
	}
	public int workTypeClassOrderDown(Integer fromId,Integer toId){
		int num = 0;
		WorkTypeClass fromWorkTypeClass = null;
		WorkTypeClass fromWorkTypeClassUp = null;
		WorkTypeClass toWorkTypeClass = null;
		fromWorkTypeClass = workTypeClassMapper.selectByPrimaryKey(fromId);
		fromWorkTypeClassUp = workTypeClassMapper.selectWorkTypeClassBySortNum(fromId);
		toWorkTypeClass = workTypeClassMapper.selectByPrimaryKey(toId);
		if(fromWorkTypeClassUp == null){
			fromWorkTypeClass.setSortNum(toWorkTypeClass.getSortNum());
			toWorkTypeClass.setSortNum(fromId);
		}else{
			fromWorkTypeClassUp.setSortNum(fromWorkTypeClass.getSortNum());
			fromWorkTypeClass.setSortNum(toWorkTypeClass.getSortNum());
			toWorkTypeClass.setSortNum(fromId);
		}
		if(null != fromWorkTypeClassUp){
			num += workTypeClassMapper.updateByPrimaryKeySelective(fromWorkTypeClassUp);
		}
		num += workTypeClassMapper.updateByPrimaryKeySelective(fromWorkTypeClass);
		num += workTypeClassMapper.updateByPrimaryKeySelective(toWorkTypeClass);
		return num;
	}
	
	/**
	 * 用于返回根据 sortNum 排序后的，列表
	 *  juchengyang 2017年2月16日
	 */
	public List<WorkTypeClass> WorkTypeClassOrder(List<WorkTypeClass> getList) throws BusinessException{
		checkList(getList);
		int size = getList.size();
		List<WorkTypeClass> returnList = new ArrayList<>();
		for(WorkTypeClass temp:getList){
			//最后一位 sortNum 为0
			if(0 == temp.getSortNum()){
				returnList.add(temp);
			}
		}
		WorkTypeClass tempWorkTypeClass = returnList.get(0);
		while(returnList.size()<size){
			for(int i = 0; i<size; i++){
				if(tempWorkTypeClass.getId().equals(getList.get(i).getSortNum())){
					returnList.add(getList.get(i));
					tempWorkTypeClass = getList.get(i);
				}
			}
		}
		for(int i=0; i<size/2; i++){
			WorkTypeClass tempProjecType = returnList.get(i);
			returnList.set(i, returnList.get(size-i-1));
			returnList.set(size-i-1, tempProjecType);
		}
		return returnList; 
	}
	/*
	 * 数据校验
	 */
	public void checkList (List<WorkTypeClass> list) throws BusinessException{
    	Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
        Map<Integer, Integer> nextMap = new HashMap<Integer, Integer>();
        for( WorkTypeClass n: list){
        	if (nextMap.containsKey(n.getSortNum())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：next重复");
            }
        	if (n.getSortNum().equals(n.getId())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：指向自己");
            }
        	keyMap.put(n.getId(), n.getSortNum());
            nextMap.put(n.getSortNum(), 0);
        }
        if(!nextMap.containsKey(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("数据出错：不存在0（最后一位标识）");
        }
        for (WorkTypeClass n : list) {
            Integer next = keyMap.get(n.getId());
            if (next.equals(0)) {
            	if(!nextMap.containsKey(n.getId()) && nextMap.size()>1){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("没有指向最后一位的");
            	}
            	if(nextMap.get(next).equals(1)){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("数据出错，最后一位不唯一");
            	}else{
            		nextMap.put(next, 1);
            	}
            	
            } else {
            	if(keyMap.containsKey(next)){
	            	if(nextMap.get(next).equals(1)){
	            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//	            		logger.info("数据出错，"+next+"重复");
	            	}else{
	            		nextMap.put(next, 1);
	            	}
            	}else{
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info(next+" 没有对应的 id");
            	}
            }

        }
        if(nextMap.containsValue(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("next 有无效值");
        }
    }
}
